package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author CC
 * time 2024-06-03
 * description
 */
@Service
@Slf4j
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {


    @Override
    public ResponseResult login(AdUserDto dto) {
        if (dto==null || StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        AdUser one = getOne(Wrappers.lambdaQuery(AdUser.class).eq(AdUser::getName, dto.getName()));
        if (one==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户信息不存在");
        }
        String salt = one.getSalt();
        String password = dto.getPassword();
        String pswd = salt==null || salt.isEmpty()?password : DigestUtils.md5DigestAsHex((password + salt).getBytes());
        if(!pswd.equals(one.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //1.3 返回数据  jwt  user
        String token = AppJwtUtil.getToken(one.getId().longValue());
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        one.setSalt("");
        one.setPassword("");
        map.put("user",one);
        return ResponseResult.okResult(map);
    }
}
